package com.example.springmall.service;

import com.example.springmall.entity.SysUser;
import com.example.springmall.exception.BusinessException;
import com.example.springmall.mapper.SysUserMapper;
import com.example.springmall.request.LoginRequest;
import com.example.springmall.request.RegisterRequest;
import com.example.springmall.util.JwtUtil;
import com.example.springmall.util.MD5Util;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
@RequiredArgsConstructor
public class SysUserService {

    private final SysUserMapper sysUserMapper;

    public String login(LoginRequest request) {
        // 1. 参数校验
        if (StringUtils.isEmpty(request.getUsername()) || StringUtils.isEmpty(request.getPassword())) {
            throw new BusinessException("用户名或密码不能为空");
        }
        // 验证码校验

        // 2. 查询用户
        SysUser sysUser = sysUserMapper.login(request.getUsername(), MD5Util.encrypt(request.getPassword()));
        if (sysUser == null) {
            throw new BusinessException("用户名或密码错误");
        }

        // 3. 生成token
        String token = JwtUtil.generateToken(sysUser.getId());

        // 4.插入用户登录记录
        return token;
    }

    public void register(RegisterRequest request) {
        // 1. 参数校验
        if (StringUtils.isEmpty(request.getUsername()) || StringUtils.isEmpty(request.getPassword())) {
            throw new BusinessException("用户名或密码不能为空");
        }

        // 2. 检查用户名是否已存在
        SysUser existSysUser = sysUserMapper.getByUsername(request.getUsername());
        if (existSysUser != null) {
            throw new BusinessException("用户名已存在");
        }

        // 3. 创建用户
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(request, sysUser);
        // 密码加密
        sysUser.setPassword(MD5Util.encrypt(request.getPassword()));

        sysUserMapper.register(sysUser);
    }

}